package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.DianDaiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 点贷 APIB
 */
@Service
public class DianDaiAPIPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5();

        long timestamp = System.currentTimeMillis() / 1000;

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", pushApiKeyParam.getApiCode());
        paramMap.put("phone", mobileMd5);
        paramMap.put("idnum", memberSourceInfo.getIdcard());
        paramMap.put("age", memberSourceInfo.getAge());
        paramMap.put("gender", memberSourceInfo.getSex() == 1 ? "男" : "女");
        paramMap.put("working_city", memberSourceInfo.getCity());
        paramMap.put("loan_amount", DianDaiUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("gjj", DianDaiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("shebao", DianDaiUtil.getshebao(memberSourceInfo.getShebao()));
        paramMap.put("credit", "无");
        paramMap.put("insurance", DianDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("house", DianDaiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("car", DianDaiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("huabei", DianDaiUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("baitiao", DianDaiUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        paramMap.put("license", "无");
        paramMap.put("zhima", DianDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("credit_record", DianDaiUtil.getyuqi(memberSourceInfo.getYuqi()));
        paramMap.put("time", timestamp);
        String signStr = StrUtil.format("{}{}{}{}", pushApiKeyParam.getApiCode(), mobileMd5, timestamp, pushApiKeyParam.getApiKey());
        String sign = SecureUtil.md5(signStr).toLowerCase();
        paramMap.put("sign", sign);

        log.info("【点贷】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【点贷】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            String backUrl = resultObject.getString("back_url");

            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        long timestamp = System.currentTimeMillis() / 1000;

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", pushApiKeyParam.getApiCode());
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("idnum", memberSourceInfo.getIdcard());
        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("age", memberSourceInfo.getAge());
        paramMap.put("gender", memberSourceInfo.getSex() == 1 ? "男" : "女");
        paramMap.put("working_city", memberSourceInfo.getCity());
        paramMap.put("loan_amount", DianDaiUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("gjj", DianDaiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("shebao", DianDaiUtil.getshebao(memberSourceInfo.getShebao()));
        paramMap.put("credit", "无");
        paramMap.put("insurance", DianDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("house", DianDaiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("car", DianDaiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("huabei", DianDaiUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("baitiao", DianDaiUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        paramMap.put("license", "无");
        paramMap.put("zhima", DianDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("credit_record", DianDaiUtil.getyuqi(memberSourceInfo.getYuqi()));
        paramMap.put("time", timestamp);
        String signStr = StrUtil.format("{}{}{}{}", pushApiKeyParam.getApiCode(), memberSourceInfo.getMobile(), timestamp, pushApiKeyParam.getApiKey());
        String sign = SecureUtil.md5(signStr).toLowerCase();
        paramMap.put("sign", sign);

        log.info("【点贷】导单开始【requestUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【点贷】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            String backUrl = resultObject.getString("back_url");
            pushApiResult.setOutOrderNo(memberSourceInfo.getMobileMd5());
            pushApiResult.setApproveUrl(backUrl);
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }

        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());

        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();

        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        JSONObject jsonObject = JSON.parseObject(paramContent);
        String phone_md5 = jsonObject.getString("phone_md5");

        noticeParamDTO.setOutOrderNo(phone_md5);
        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setQueryResult(paramContent);

        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        noticeParamDTO.setSettleFlag(true);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(phone_md5));
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }


}
